package com.zou.lotterylucky

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.os.SystemClock
import android.util.Log
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.zou.lotterylucky.utils.SPUtils
import org.json.JSONObject
import java.util.*

/**
 * 描述：时间同步服务
 * <p>
 * 作者：王俊
 * 日期：2021/5/30
 */
class TimeSyncService : Service() {
    companion object {
        const val TAG = "TimeSyncService"
    }

    private lateinit var requestQueue: RequestQueue

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        requestQueue = Volley.newRequestQueue(this)
        Timer().scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                syncTime()
            }
        }, 0, 4000)
    }

    fun syncTime() {
        requestQueue.add(
            StringRequest(
                Request.Method.GET,
                "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp",
                {
                    try {
                        val jsonObject = JSONObject(it)
                        //获取到时间戳
                        val timeLong = jsonObject.getJSONObject("data").getString("t").toLong()

                        //记录下现在的 elapsedRealtime
                        val elapsedRealtime = SystemClock.elapsedRealtime()
                        SPUtils.set(
                            LotteryApp.context,
                            Constants.SP_SYNC_elapsedRealTime,
                            elapsedRealtime
                        )
                        //存储服务器的时间戳
                        SPUtils.set(
                            LotteryApp.context,
                            Constants.SP_SYNC_currentTimeMillis,
                            timeLong
                        )
//                        Log.d(TAG, "成功同步 $timeLong  $elapsedRealtime")
                    } catch (e: Exception) {

                    }
                },
                {
                    Log.d(TAG, "成功失败 ${it.message.toString()}")
                })
        )
    }
}